package com.faxsun.core.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import mtons.modules.pojos.UserProfile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.transaction.annotation.Transactional;

import com.faxsun.core.persist.dao.BlacklistDao;
import com.faxsun.core.persist.dao.LiveDao;
import com.faxsun.core.persist.dao.LiveInteractionDao;
import com.faxsun.core.persist.dao.LiveManagerDao;
import com.faxsun.core.persist.entity.BlacklistPO;
import com.faxsun.core.persist.entity.LiveManagerPO;
import com.faxsun.core.persist.entity.LivePO;
import com.faxsun.core.persist.entity.UserPO;
import com.faxsun.core.service.LiveAdminService;
import com.faxsun.pojos.view.Live;

/**
 * 
 * @author zhilin
 * @since Jun 18, 2015
 */
@Transactional
public class LiveAdminServiceImpl implements LiveAdminService {
	private static final Logger logger = LoggerFactory
			.getLogger(LiveAdminServiceImpl.class);
	@Autowired
	LiveDao liveDao;
	@Autowired
	BlacklistDao blacklistDao;
	@Autowired
	LiveManagerDao liveManagerDao;
	@Autowired
	LiveInteractionDao liveInteractionDao;

	@Override
	@Transactional
	public LivePO updateLiveName(long id, String name) {
		LivePO live = liveDao.get(id);
		if (live == null) {
			logger.warn("live id error, no match live find!");
		}
		live.setTopic(name);
		liveDao.update(live);
		return live;
	}

	@Override
	@Transactional
	public LivePO updateLiveGroup(long id, String group) {
		// TODO 需要对直播分组时实现。
		return null;
	}

	@Override
	@Caching(evict = {
			@CacheEvict(value = "blacklistCache", key = "'ids'+new String(#liveId)", beforeInvocation = true),
			@CacheEvict(value = "blacklistCache", key = "'profile'+new String(#liveId)", beforeInvocation = true) })
	@Transactional
	public void disableSendMsg(long liveId, long userId, long adminId) {
		BlacklistPO blacklist = new BlacklistPO();
		UserPO user = new UserPO();
		user.setId(userId);
		blacklist.setUser(user);
		blacklist.setLiveId(liveId);
		blacklist.setAdminId(adminId);
		blacklist.setCreated(new Date(System.currentTimeMillis()));
		blacklistDao.save(blacklist);
	}

	@Override
	@Caching(evict = {
			@CacheEvict(value = "blacklistCache", key = "'ids'+new String(#liveId)", beforeInvocation = true),
			@CacheEvict(value = "blacklistCache", key = "'profile'+new String(#liveId)", beforeInvocation = true) })
	@Transactional
	public void enableSendMsg(long liveId, long userId) {
		blacklistDao.remove(userId, liveId);
	}

	@Override
	@Transactional
	public LivePO save(long userId, String topic, Date startDatetime,
			Date endDatetime) {
		LivePO live = new LivePO();
		live.setTopic(topic);
		live.setStartTime(startDatetime);
		live.setEndTime(endDatetime);
		liveDao.save(live);
		live = liveDao.findByTopic(topic);
		this.saveLiveManager(live.getId(), userId);
		return live;

	}

	@Override
	@Transactional
	public LivePO save(long userId, LivePO channel) {
		boolean isCreate=channel.getId()==0L;
		liveDao.saveOrUpdate(channel);
		if (isCreate) {
			this.saveLiveManager(channel.getId(), userId);
		}
		return channel;
	}

	@Override
	@Transactional
	public void addLiveManager(long liveId, long userId) {
		this.saveLiveManager(liveId, userId);
	}

	@Caching(evict = {
			@CacheEvict(value = "liveManagerCache", key = "'manager'+new String(#userId)+new String(#liveId)", beforeInvocation = true),
			@CacheEvict(value = "liveManagerCache", key = "'managers'+new String(#liveId)", beforeInvocation = true),
			@CacheEvict(value = "liveManagerCache", key = "'managersIds'+new String(#liveId)", beforeInvocation = true) })
	private void saveLiveManager(long liveId, long userId) {

		LiveManagerPO manager = new LiveManagerPO();
		manager.setLiveId(liveId);
		manager.setUserId(userId);
		List<LiveManagerPO> lists = liveManagerDao.findAllManagers(liveId);
		if (lists == null || lists.size() == 0) {
			manager.setManagerRole(Roles.ADMIN.toString());
		} else {
			manager.setManagerRole(Roles.MANAGER.toString());
		}
		manager.setCreated(Calendar.getInstance().getTime());
		liveManagerDao.saveOrUpdate(manager);
	}

	public enum Roles {
		ADMIN, MANAGER;
	}

	@Override
	@Transactional
	public List<LivePO> getMyLive(long userid) {
		return liveManagerDao.find(userid, Roles.ADMIN.toString());
	}

	@Override
	@Transactional
	public List<Long> getTalkDisabledUserId(long liveId) {
		return blacklistDao.getChannelDisabledBlackist(liveId);

	}

	@Override
	@Transactional
	public List<UserProfile> getTalkDisabledUser(long liveId) {
		return blacklistDao.getChannelDisabledUserList(liveId);
	}

	@Override
	@Cacheable(value = "liveManagerCache", key = "'manager'+new String(#userId)+new String(#liveId)", condition = "#result!=null")
	@Transactional
	public LiveManagerPO getLiveManager(long userId, long liveId) {
		return liveManagerDao.find(liveId, userId);
	}

	@Override
	@Cacheable(value = "liveManagerCache", key = "'managers'+new String(#liveId)", condition = "#lists!=null&&#lists.size()>0")
	public List<LiveManagerPO> getLiveManagers(long liveId) {
		List<LiveManagerPO> lists = liveManagerDao.findAllManagers(liveId);
		if (lists.size() == 0)
			lists = null;
		return lists;
	}

	@Override
	@Cacheable(value = "liveManagerCache", key = "'managersIds'+new String(#liveId)", condition = "#ids!=null&&#ids.size()>0")
	public List<Long> getLiveManagersIds(long liveId) {
		List<Long> ids = null;
		List<LiveManagerPO> managers = liveManagerDao.findAllManagers(liveId);
		if (managers.size() == 0)
			return ids;
		ids = new ArrayList<Long>();
		for (LiveManagerPO m : managers) {
			ids.add(m.getUserId());
		}
		return ids;
	}

	@Override
	@Cacheable(value = "liveManagerCache", key = "'getLiveAdmin'+#liveId")
	public LiveManagerPO getLiveAdmin(long liveId) {
		return liveManagerDao.getLiveAdmin(liveId);
	}

	@Override
	public List<Live> getMyLiveWithNop(long userId) {
		List<LivePO> livePOs = getMyLive(userId);
		List<Live> lives = new ArrayList<Live>();
		for (LivePO live : livePOs) {
			Live item = Live.bulid(live);
			item.setNop(liveInteractionDao.getLiveNop(live.getId()).longValue());
			lives.add(item);
		}
		return lives;
	}

	@Override
	@CacheEvict(value = "liveManagerCache", key = "'manager'+new String(#userid)+new String(#liveid)", beforeInvocation = true)
	public boolean removeManager(long liveid, long userid) {
		LiveManagerPO po = this.getLiveManager(userid, liveid);
		if (po != null) {
			this.liveManagerDao.delete(po);
			return true;
		} else
			return false;
	}

}
